package com.atom.dbflow

import android.content.Context
import android.content.ContextWrapper
import android.database.DatabaseErrorHandler
import android.database.sqlite.SQLiteDatabase
import android.text.TextUtils
import android.util.Log
import com.raizlabs.android.dbflow.config.FlowLog
import com.raizlabs.android.dbflow.config.FlowManager
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream


class DBFlowContext : ContextWrapper {

    companion object {
        //初始化数据库
        fun initDB(context: Context, file: File): ContextWrapper {
            return DBFlowContext(context, file)
        }

        //重新加载数据库
        fun deleteDB(context: Context, file: File) {
            file.delete()
            FlowManager.destroy()
        }
    }

    private val file: File
    private val context: Context

    constructor(
        base: Context,
        file: File
    ) : super(base) {
        if(!file.exists()){
            file.mkdirs()
        }
        this.file = file
        this.context = base
    }

    override fun getApplicationContext(): Context {
        return this
    }

    override fun getDatabasePath(name: String?): File {
        Log.e("DBFlowContext", "获取数据库路径 $name")
        if(name == null || name.isEmpty()){
            return super.getDatabasePath(name)
        }
        if(!file.exists()){
            file.mkdirs()
        }
        // 数据库文件是否创建成功
        var isFileCreateSuccess = false
        // 判断文件是否存在，不存在则创建该文件
        val dbFile = File(file , name)
        if (!dbFile.exists()) {
            try {
                isFileCreateSuccess = dbFile.createNewFile() // 创建文件
            } catch (e: IOException) {
                Log.e("DBFlowContext", " ${e.localizedMessage}")
                e.printStackTrace()
            }
        } else isFileCreateSuccess = true
        // 返回数据库文件对象
        Log.e("DBFlowContext", "创建成功 了么 $isFileCreateSuccess")
        //return context.getDatabasePath(name)
        return if (isFileCreateSuccess) dbFile else super.getDatabasePath(name)
    }

    override fun openOrCreateDatabase(
        name: String?,
        mode: Int,
        factory: SQLiteDatabase.CursorFactory?
    ): SQLiteDatabase {
        Log.e("DBFlowContext", "openOrCreateDatabase 2 获取数据库路径 $name")
        return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null)
    }

    override fun openOrCreateDatabase(
        name: String?,
        mode: Int,
        factory: SQLiteDatabase.CursorFactory?,
        errorHandler: DatabaseErrorHandler?
    ): SQLiteDatabase {
        Log.e("DBFlowContext", "openOrCreateDatabase 3 获取数据库路径 $name")
        return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null)
    }

}